package org.mongodb;

import java.net.UnknownHostException;
import java.util.List;

import org.acquaintance.I_CRUD;
import org.bson.types.ObjectId;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;

public class MongoFacade implements I_CRUD{
	
	private DB db;
	private DBCollection coll;
	
	public MongoFacade(){
		MongoClient mongoClient = null;
		try {
			//mongoClient = new MongoClient("localhost", 27017);
			mongoClient = new MongoClient("46.137.19.156", 27017); 
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		db = mongoClient.getDB("test");
		coll = db.getCollection("testCollection");
		//Set profile for logging
		db.command(BasicDBObjectBuilder.start().add("profile", 2).get());
	}
	
	@Override
	public void create(int repetitions, String attributeName,
			String attributeValue) {
		//Bulk insert
		BasicDBList docList = new BasicDBList();

		for(int i=0;i<repetitions;i++){
			BasicDBObject doc = new BasicDBObject().
			append(attributeName, attributeValue);
			doc.put("_id", i+"");
			docList.put(i, doc);
		}

		coll.insert((List)docList);
//		Mass inserts
//		BasicDBObject doc = new BasicDBObject().
//		append(attributeName, attributeValue);
//		for(int i=0;i<repetitions;i++){
//			doc.put("_id", i+"");
//			coll.insert(doc);
//		}
	}

	@Override
	public void read() {
		int i =0;
		DBCursor cursor = coll.find();
		try {
            while(cursor.hasNext()) {
            	i=i+1;
                String records = cursor.next()+"\n";
            }
        } finally {
            cursor.close();
        }
        System.out.println(i);
	}

	@Override
	public void delete() {
		coll.remove(new BasicDBObject());
	}

	private void cleanCollection(){
		if(coll.count()>0){
			coll.remove(new BasicDBObject());
		}
	}

	@Override
	public void update(String attributeName, String attributeValue) {
		for(int i =0;i<10;i++){
			BasicDBObject query = new BasicDBObject().append("$set", 
					new BasicDBObject().put("_id",new BasicDBObject("$lt",25)));
			
				BasicDBObject newDoc = new BasicDBObject().append("$set", 
				new BasicDBObject().append("type"+i, attributeValue));
				coll.update(query,newDoc,false,true);
		}
		System.out.println("Update done");
	}
}
